package com.cu.simpleerp.frame.filter;

import com.cu.simpleerp.frame.SpringContextUtil;
import com.cu.simpleerp.frame.session.SessionManager;
import com.cu.simpleerp.frame.session.SessionManagerUtil;
import com.cu.simpleerp.util.StringUtil;
import org.slf4j.MDC;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.UrlPathHelper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 请求过滤处理，日志key添加和登录验证
 *
 * @author jintian
 * @date 2018/10/23 15:16
 */
public class LoginFilter extends HandlerInterceptorAdapter {

    private UrlPathHelper urlPathHelper = new UrlPathHelper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // log4j key清除
        MDC.clear();
        // 日志中放一个 key 便于日志查看
        MDC.put("key", StringUtil.UUIDStr());

        // 判断用户是否登录,切为需要登录的地址
        if (checkLogin(request) && checkUrl(request)) {
            // 返回登录界面
            response.sendRedirect("/static/login.html");
            return false;
        } else {
            // 刷新cookie
            refashSession(request);
            return true;
        }
    }

    private boolean checkUrl(HttpServletRequest request) {
        String requestUri = request.getRequestURI();
        return !requestUri.startsWith("/login");
    }


    /**
     * 刷新session
     *
     * @param request
     */
    private void refashSession(HttpServletRequest request) {
        SessionManagerUtil.refashSession(request);
    }

    private boolean checkLogin(HttpServletRequest request) {
        return SessionManagerUtil.checkSession(request);
    }
}
